Ext.define('CDR.widget.PBXFactory', {
	extend: 'Ext.Panel',
	alias : 'widget.pbxfactory',
	title: CDR.I18N['pbx.factory.title'],
	selectedFactoryId : 0,
	selectedFactory: null,
	pbx: null,
	profileCenter : null,
	initComponent: function() {
		var me = this;
		me.callParent();
		me.win = Ext.createWidget('globalpopup', {title: CDR.I18N['pbx.factory.new'], url:'create-pbx-factory',
				addFields: [{xtype:'hidden', name:'factoryId'}], checkOn:'PBX_FACTORY',targetObject: me});
		me.pbx = Ext.createWidget('pbx',{pbxFactory:me});
		//ajax to load items
		Ext.Ajax.request({
			async: false,
			url: 'list-pbx-factory',
			success: function(response, opts) {
				var obj = Ext.decode(response.responseText);
				Ext.each(obj.results, function(item){
					this.addItem(item.name, item.description, item.id);
				}, me);
			}
		});
	},
	layout:'anchor',
	dockedItems: [{
		xtype: 'toolbar',
		items: [{
			text: CDR.I18N['pbx.factory.new'],
			iconCls: 'icon-add',
			handler: function() {
				var me = this.up('panel');
				me.win.setTitle(CDR.I18N['pbx.factory.new']);
				me.win.type = CDR.Constant.WINDOW_NEW_MODE;
				me.win.form.getForm().reset();
				me.win.show();
			}
		}, '-' ,{
			text: CDR.I18N['pbx.factory.edit'],
			iconCls: 'icon-edit',
			handler: function() {
				var me = this.up('panel');
				if(me.selectedFactoryId == 0){
					Ext.Msg.alert('Failed', "Please seletect a factory");
					return;
				}
				me.win.setTitle(CDR.I18N['pbx.factory.edit']);
				me.win.type = CDR.Constant.WINDOW_EDIT_MODE;
				me.win.form.getForm().reset();
				
				//get pbx and popular data form
				Ext.Ajax.request({
					method: 'GET',
					url:'pbx-factory-info',
					params:{'pbxFactoryId': me.selectedFactoryId},
					success: function(response, opts){
						var obj = Ext.decode(response.responseText);
						me.win.addFieldValues = [{name: 'factoryId', value: me.selectedFactoryId}];
						me.win.editData(obj);
						me.win.show();
					}
				});
				
			}
		}]
	}], 
	addItem: function(name, description, id){
		var me = this;
		var com = Ext.createWidget('button',{
			obId: id,
			id: 'button-pbxfactory-' + id,
			anchor:'100%',
            text    : name,
			scale: 'large',
			margin: '0 0 10px 0',
			enableToggle: true,
			toggleGroup:'serviceprovider_bnt',
			handler: function(){
				me.selectedFactoryId = this.obId;
				me.selectedFactory = this;
				//get list
				if (me.pbx) {
					var store = me.pbx.view.store;
					store.setProxy({
					  type: 'ajax',
					  url : 'list-pbx-view?pbxFactoryId=' + me.selectedFactoryId,
					  reader: {
						  type: 'json',
						  root: 'results'
					  }
					});
					store.load();
				}
			}, tooltip: description
		});
		this.add(com);
		return com;
	},
	submitOk: function(data, type) {
		if (type === CDR.Constant.WINDOW_EDIT_MODE) {
			this.selectedFactory.setText(data.name);
			this.selectedFactory.setTooltip(data.description);
		} else if(type === CDR.Constant.WINDOW_NEW_MODE){
			this.addItem(data.name, data.id);
		}
	},
	listeners: {
		expand : function(){
			this.profileCenter.removeAll(false);
			this.profileCenter.add(this.pbx);
		}
	}
});

//create trunk view
Ext.define('CDR.widget.PBXView', {
  extend: 'Ext.view.View',
  alias : 'widget.pbxview',
  targetObject: null,
  tpl: [
      '<tpl for=".">',
          '<div class="thumb-wrap" data-qtip="{description}">',
              '<div class="thumb">',
                  (!Ext.isIE6? '<img src="resources/app/images/{thumb}" />' : 
                  '<div style="width:76px;height:76px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'resources/app/images/{thumb}\')"></div>'),
              '</div>',
              '<span>{name}</span>',
          '</div>',
      '</tpl>'
  ],
  itemSelector: 'div.thumb-wrap',
  multiSelect: false,
  singleSelect: true,
  cls: 'x-image-view',
  autoScroll: true,
  bodyStyle:'background-color: white;',
  initComponent: function() {
      this.store = Ext.create('Ext.data.Store', {
          fields: ['name', 'thumb', 'obId']
      });
	  this.menu = Ext.createWidget('menu',{
		items:[{
				text: 'Add Profile',
				iconCls: 'icon-add',
				handler: function() {
					this.targetObject.addProfile(this.getSelectionModel().getLastSelected());
				},
				scope: this
			}, {
				text: 'Delete',
				iconCls: 'icon-delete',
				handler: function() {
					
				},
				scope: this
		}]
	});
	this.callParent();
  },
  listeners: {
	itemdblclick: function(me, r){
		if(this.targetObject){
			this.targetObject.proccessDbclick(r);
		}
	},
	itemcontextmenu:function(el, r, node, index, e, eOpts){
		this.select(r);
		this.menu.showAt(e.xy);
		e.stopEvent();
	}
  }
});

Ext.define('CDR.widget.PBX', {
	extend: 'Ext.Panel',
	alias : 'widget.pbx',
	pbxFactory: null,
	layout: 'border',
	border: false,
	currentPbx: null,
	initComponent: function() {
		var me = this;
		me.callParent();
		me.view = Ext.createWidget('pbxview',{region:'center', targetObject: me});
		me.formContainer = Ext.create('widget.container', {
			region:'south',
			height:'50%',
			layout:'fit',
			split: true
		});
		me.add(me.formContainer);
		me.add({xtype: 'panel', region:'center', layout:'fit',items:[me.view]});
		me.pbxForm = Ext.createWidget('pbxform', {region: 'center', url:'create-pbx', addFields: [{xtype:'hidden', name:'factoryId'}, {xtype:'hidden', name:'pbxId'}], targetObject: me});
		
		me.profile = Ext.create('CDR.widget.Profile', {url: 'save-profile'});
	},
	dockedItems: [{
		xtype: 'toolbar',
		items: [{
			text: CDR.I18N['pbx.new'],
			iconCls: 'icon-add',
			handler: function(){
				var me =  this.up('panel');
				if(me.pbxFactory.selectedFactoryId == 0){
					Ext.Msg.alert('Failed', "Please seletect a factory");
					return;
				}
				me.formContainer.removeAll(false);
				me.pbxForm.addFieldValues = [{name: 'factoryId', value: me.pbxFactory.selectedFactoryId}];
				me.pbxForm.initData();
				me.pbxForm.getForm().reset();
				me.formContainer.add(me.pbxForm);
			}
		}, '-', '', {
			fieldLabel: CDR.I18N['label.search'],
			labelWidth: 45,
			xtype: 'textfield',
			listeners: {
				'change': function(me, newVal, oldVal){
					var me =  this.up('panel');
					me.view.store.clearFilter();
					me.view.store.filter(new Ext.util.Filter({
							filterFn: function(item) {
								var searchtest,namematch;
								var escapere = Ext.String.escapeRegex;
								searchtest = new RegExp(escapere(newVal), 'i');
								namematch = searchtest.test(item.data.name);
								return namematch;
							}
						})
					);
				}
			}
			
		}]
	}],
	submitOk: function(data, type) {
		if(type === CDR.Constant.WINDOW_NEW_MODE){
			this.view.store.add({name: data.name, obId: data.obId, thumb: data.thumb});
		} else if(type === CDR.Constant.WINDOW_EDIT_MODE){
			this.currentPbx.set('name', data.name);
		}
		
	},
	proccessDbclick: function(r){
		this.currentPbx = r;
		var id = r.data.obId;
		this.pbxForm.getForm().reset();
		Ext.Ajax.request({
			scope: this,
			async: false,
			url: 'pbx-info?pbxId=' + id,
			success: function(response, opts) {
				var obj = Ext.decode(response.responseText);
				this.pbxForm.addFieldValues = [{name: 'factoryId', value: obj.result.factoryId},{name: 'pbxId', value: obj.result.obId}];
				this.pbxForm.editData(obj);
			}
		});
		this.formContainer.removeAll(false);
		this.formContainer.add(this.pbxForm);
	},
	addProfile: function(seletedNode){
		this.formContainer.removeAll(false);
		this.profile.reloadData(seletedNode);
		this.formContainer.add(this.profile);
	}
});
